package org.dizena.config;

import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.dizena.base.jwt.JwtFilter;
import org.dizena.base.shiro.TokenUserRealm;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

//@Configuration
public class ShiroTokenConfig
{

    //@Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager)
    {
        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("jwt", new JwtFilter());

        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setFilters(filterMap);
        factoryBean.setSecurityManager(securityManager);
        factoryBean.setLoginUrl("/api/v1/auth/login");
        factoryBean.setUnauthorizedUrl("/api/v1/auth/none");

        Map<String, String> filterRuleMap = new HashMap<>();
        filterRuleMap.put("/", "anon");
        filterRuleMap.put("/error", "anon");
        filterRuleMap.put("/api/**", "anon");
        filterRuleMap.put("/**", "jwt,authc");
        factoryBean.setFilterChainDefinitionMap(filterRuleMap);
        return factoryBean;
    }

    //@Bean
    public SecurityManager securityManager(TokenUserRealm realm)
    {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);

        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);

        securityManager.setSubjectDAO(subjectDAO);
        return securityManager;
    }


}
